package com.jiawa.wiki.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jiawa.wiki.domain.User;
import com.jiawa.wiki.domain.UserExample;
import com.jiawa.wiki.exception.BusinessException;
import com.jiawa.wiki.exception.BusinessExceptionCode;
import com.jiawa.wiki.mapper.UserMapper;
import com.jiawa.wiki.req.UserLoginReq;
import com.jiawa.wiki.req.UserQueryReq;
import com.jiawa.wiki.req.UserResetPasswordReq;
import com.jiawa.wiki.req.UserSaveReq;
import com.jiawa.wiki.response.PageResp;
import com.jiawa.wiki.response.UserLoginResp;
import com.jiawa.wiki.response.UserResp;
import com.jiawa.wiki.utils.CopyUtil;
import com.jiawa.wiki.utils.SnowFlake;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.List;

@Service
public class UserService {

    @Resource
    private UserMapper userMapper;

    @Resource
    private SnowFlake snowFlake;

    private final static Logger LOG = LoggerFactory.getLogger(UserService.class);

    /**
     * name模糊查询
     * 支持分页查询：注意 PageHelper 只对一条查询sql有效，如果配置下有多个sql,应该写在要查询的sql上即可
     * @param req
     * @return
     */
    public PageResp<UserResp> list(UserQueryReq req) {
        UserExample userExample = new UserExample();
        UserExample.Criteria criteria = userExample.createCriteria();
        // 动态sql判断有没有name
        if (!ObjectUtils.isEmpty(req.getLoginName())) {
            criteria.andNameLike("%" + req.getLoginName() + "%");
        }
        PageHelper.startPage(req.getPageNum(), req.getPageSize());
        List<User> userList = userMapper.selectByExample(userExample);

        PageInfo<User> pageInfo = new PageInfo<>(userList);
        LOG.info("总页数：{}", pageInfo.getPages());
        LOG.info("总行数：{}", pageInfo.getTotal());
        // 持久层的需要传化为 List<UserResp>
        /* List<UserResp> respList = new ArrayList<>();
         for (User user : userList) {
            UserResp userResp = new UserResp();
            //BeanUtils.copyProperties(user, userResp);
            // 单体复制
            UserResp copy = CopyUtil.copy(user, UserResp.getClass());
            respList.add(copy);
        } */

        // 列表复制 上述代码简化
        List<UserResp> respList = CopyUtil.copyList(userList, UserResp.class);

        PageResp<UserResp> pageResp = new PageResp<>();
        pageResp.setList(respList);
        pageResp.setTotal(pageInfo.getTotal());
        LOG.info("{}", respList);
        return pageResp;
    }

    /**
     * 保存用户（看请求参数id是否为空） 修改用户
     * 添加用户需要判断是否存在
     * @param req
     */
    public void save(UserSaveReq req) {
        User user = CopyUtil.copy(req, User.class);
        if (ObjectUtils.isEmpty(user.getId())) {
            if (ObjectUtils.isEmpty(selectUser(req.getLoginName()))) {
                // 新增 设置id 此ID是雪花算法实现 不是uuid 和自增ID
                user.setId(snowFlake.nextId());
                userMapper.insert(user);
            } else {
                // 用户名已存在 抛出自定义异常。
                throw new BusinessException(BusinessExceptionCode.USER_LOGIN_NAME_EXIST);
            }
        } else {
            // 修改(登录名不可修改 前端加了disabled但是可以绕过的，所以后端需要加参数校验)
            user.setLoginName(null);
            // 修改的时候不修改密码
            user.setPassword(null);
            //userMapper.updateByPrimaryKey(user);
            // 当user有loginName才会去更新值
            userMapper.updateByPrimaryKeySelective(user);
        }
    }

    public void delete(Long id) {
        userMapper.deleteByPrimaryKey(id);
    }

    /**
     * 根据登录名 查询用户
     * @param loginName
     * @return
     */
    public User selectUser(String loginName) {
        UserExample userExample = new UserExample();
        UserExample.Criteria criteria = userExample.createCriteria();
        criteria.andLoginNameEqualTo(loginName);

        List<User> users = userMapper.selectByExample(userExample);
        if (CollectionUtils.isEmpty(users)) {
            return null;
        } else {
            return users.get(0);
        }
    }

    /**
     * 重置用户密码
     * @param req
     */
    public void resetPassword(UserResetPasswordReq req) {
        User user = CopyUtil.copy(req, User.class);
        userMapper.updateByPrimaryKeySelective(user);
    }

    /**
     * 用户登录
     * @param req
     * @return
     */
    public UserLoginResp login(UserLoginReq req) {
        User userDb = selectUser(req.getLoginName());
        if (ObjectUtils.isEmpty(userDb)) {
            LOG.info("用户名不存在，{}", req.getLoginName());
            // 用户名不存在
            throw new BusinessException(BusinessExceptionCode.LOGIN_USER_ERROR);
        } else {
            if (req.getPassword().equals(userDb.getPassword())) {
                // 登录成功
                return CopyUtil.copy(userDb, UserLoginResp.class);
            } else {
                // 密码错误
                LOG.info("密码不对，输入密码：{}，数据库密码：{}", req.getPassword(), userDb.getPassword());
                throw new BusinessException(BusinessExceptionCode.LOGIN_USER_ERROR);
            }
        }
    }
}
